package huoye.shops.guidance;

import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;


import com.codeideology.android.utils.ApkUtils;
import com.codeideology.android.utils.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Timer;
import java.util.TimerTask;

import commonality.updater.UpdateAppManager;
import huoye.shops.MainActivity;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.base.UserManager;
import huoye.shops.common.model.SMSCoder;
import huoye.shops.guidance.presenter.LaunchPresenter;
import huoye.shops.guidance.view.ILaunchView;
import huoye.shops.huoye.user.activity.LoginActivity;
import huoye.shops.huoye.user.activity.SelectCityActivity;
import huoye.shops.huoye.user.activity.SelectNewActivity;
import huoye.shops.huoye.user.model.UpdateInfo;
import huoye.shops.huoye.user.model.User;
import huoye.shops.huoye.user.presenter.LoginPresenter;
import huoye.shops.huoye.user.view.ILoginView;
import huoye.shops.sp.SharedPreferencesUtil;
import huoye.shops.widget.UpdateDialog;

public class LaunchActivity extends BaseActivity implements ILaunchView {

    String imgPath ="https://goss.veer.com/creative/vcg/veer/612/veer-132857661.jpg";


    private LaunchPresenter mLaunchPresenter;
    @Override
    protected int getContentViewId() {
        return R.layout.acitvity_launch;
    }
    private Intent localIntent;
    @Override
    protected void initView(@Nullable Bundle bundle) {
        isFirstStart();


        mLaunchPresenter = new LaunchPresenter();
        mLaunchPresenter.addTaskListener(this);
        mLaunchPresenter.onStart();
        //版本更新
        mLaunchPresenter.checkUpdate();

/*
       User user = new User();
        user.setUserId("3");
        user.setShopId("3");
        user.setiCardType(2);
        user.setPowerManage(true);
        user.setUserImg(imgPath);
        UserManager.getInstance().setUser(user);
        startActivity(MainActivity.class);*/


      /*  String certificateSHA1Fingerprint = getCertificateSHA1Fingerprint(this);
        Log.e("sha1======",certificateSHA1Fingerprint);*/
    }


   /* //这个是获取SHA1的方法
    public static String getCertificateSHA1Fingerprint(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取当前要获取SHA1值的包名，也可以用其他的包名，但需要注意，
        //在用其他包名的前提是，此方法传递的参数Context应该是对应包的上下文。
        String packageName = context.getPackageName();
        //返回包括在包中的签名信息
        int flags = PackageManager.GET_SIGNATURES;
        PackageInfo packageInfo = null;
        try {
            //获得包的所有内容信息类
            packageInfo = pm.getPackageInfo(packageName, flags);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //签名信息
        Signature[] signatures = packageInfo.signatures;
        byte[] cert = signatures[0].toByteArray();
        //将签名转换为字节数组流
        InputStream input = new ByteArrayInputStream(cert);
        //证书工厂类，这个类实现了出厂合格证算法的功能
        CertificateFactory cf = null;
        try {
            cf = CertificateFactory.getInstance("X509");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //X509证书，X.509是一种非常通用的证书格式
        X509Certificate c = null;
        try {
            c = (X509Certificate) cf.generateCertificate(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String hexString = null;
        try {
            //加密算法的类，这里的参数可以使MD4,MD5等加密算法
            MessageDigest md = MessageDigest.getInstance("SHA1");
            //获得公钥
            byte[] publicKey = md.digest(c.getEncoded());
            //字节到十六进制的格式转换
            hexString = byte2HexFormatted(publicKey);
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        }
        return hexString;
    }
    //这里是将获取到得编码进行16进制转换
    private static String byte2HexFormatted(byte[] arr) {
        StringBuilder str = new StringBuilder(arr.length * 2);
        for (int i = 0; i < arr.length; i++) {
            String h = Integer.toHexString(arr[i]);
            int l = h.length();
            if (l == 1)
                h = "0" + h;
            if (l > 2)
                h = h.substring(l - 2, l);
            str.append(h.toUpperCase());
            if (i < (arr.length - 1))
                str.append(':');
        }
        return str.toString();

    }*/



    private void isFirstStart(){
        // 是否第一次安装
        SharedPreferencesUtil shared=new SharedPreferencesUtil(this, APIUrls.CONFIG);
        boolean isFirstStart = shared.getBoolean( APIUrls.IS_FIRST_START);
        if (!isFirstStart) {
            localIntent= new Intent(this, GuideActivity.class);
            shared.putBoolean(APIUrls.IS_FIRST_START,true);
        } else {
            if(StringUtils.isNotEmpty(UserManager.getInstance().getUserId())){
                localIntent = new Intent(this, MainActivity.class);
            }else if(StringUtils.isNotEmpty(UserManager.getInstance().getCity())){
                localIntent = new Intent(this, LoginActivity.class);
            }else {
                localIntent = new Intent(this,SelectNewActivity.class);

            }

        }

    }


    @Override
    public void onCheckUpdate(UpdateInfo info) {
        // 检查升级
        showUpdate(info);
    }


    private String mDownloadUrl = "";
    /**
     * 升级提示
     *
     * @param info
     */
    private void showUpdate(final UpdateInfo info) {
        this.mDownloadUrl = info.getDownUrl();
        String versionName = ApkUtils.getVersionName(this);
        Log.e("test",versionName);
        if(Float.valueOf(versionName) >= Float.valueOf(info.getAppVerno())){
           showLaunch();
        }else {
            showDialogUpdater(info);
        }
    }

    private void  showLaunch(){
        Timer timer=new Timer();
        TimerTask tast=new TimerTask() {
            @Override
            public void run(){
                startActivity(localIntent);
                LaunchActivity.this.finish();
            }
        };
        timer.schedule(tast,2000);
    }



    private void showDialogUpdater(UpdateInfo info){
        UpdateDialog updateDialog = new UpdateDialog(this);
        updateDialog.setOnUpdateListener(new UpdateDialog.OnUpdateListener() {
            @Override
            public void onUpdateClick() {
                update(info);
            }
        });
        updateDialog.show();
        updateDialog.setDialogContent(info.getAppVerno()+"",info.getSize(),info.getUpContent());
    }

    private void update(UpdateInfo info){
        UpdateAppManager.downloadApkS(this, info.getDownUrl(), getResources().getString(R.string.app_name), "帮播侠");
    }


}
